import random
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from celery_tasks.sms.tasks import send_sms_code
# redis中短信验证码有效时间：s
from meiduo_mall.libs.yuntongxun.sms import CCP

SMS_CODE_REDIS_EXPIRES = 300
# 发送短信验证码时间间隔：s
SEND_SMS_CODE_INTERVAL = 60
# 云通讯发送短信模板ID
SMS_CODE_TEMP_ID = 1


class SMSCodeView(APIView):
    """发送短信验证码"""

    def get(self, request, mobile):
        # 判断短信验证码是否在60s内
        redis_conn = get_redis_connection('verify_codes')
        send_flag = redis_conn.get("send_flag_%s" % mobile)
        if send_flag:
            return Response({"message":"请求次数太频繁，请稍后再试"},status=status.HTTP_400_BAD_REQUEST)
        # 生成随机的6位验证码
        sms_code = '%06d' % random.randint(0, 999999)

        # 保存短信验证码跟发送记录
        print(sms_code)
        p1 = redis_conn.pipeline()
        p1.setex("sms_%s" % mobile, SMS_CODE_REDIS_EXPIRES, sms_code)
        p1.setex("send_flag_%s" % mobile, SEND_SMS_CODE_INTERVAL, 1)
        p1.execute()

        # 发送短信
        sms_code_expires = SMS_CODE_REDIS_EXPIRES // 60
        # try:
        #     ccp = CCP()
        #     res = ccp.send_template_sms(mobile, [sms_code, sms_code_expires], SMS_CODE_TEMP_ID)
        # except Exception as e:
        #     return Response({"message": "发送短信异常"}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
        # if res != 0:
        #     return Response({"message": "发送短信失败"}, status=status.HTTP_503_SERVICE_UNAVAILABLE)
        # send_sms_code.delay(mobile,sms_code, sms_code_expires)
        return Response({"message": "OK"})
